package com.knife.blog.logic;

import java.io.File;
import java.util.Map;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;

public class ImgService {
	String fromdir; // fromdir 图片的原始目录

	String todir; // todir 处理后的图片存放目录

	String imgfile; // imgfile 原始图片

	String sysimgfile; // sysimgfile 处理后的图片文件名前缀

	public ImgService(String fromdirNow, String todirNow, String imgfileNow,
			String sysimgfileNow) {
		fromdir = fromdirNow;
		todir = todirNow;
		imgfile = imgfileNow;
		sysimgfile = sysimgfileNow;
	}

	public boolean CreateThumbnail(int width,int height) throws Exception {
		double Ratio = 0.0;
		File F = new File(fromdir, imgfile);
		if (!F.isFile())
			throw new Exception(F + " is not image file error in CreateThumbnail!");
		File ThF = new File(todir, sysimgfile);

		BufferedImage Bi = ImageIO.read(F);
		
		Image Itemp = Bi.getScaledInstance(width, height, Bi.SCALE_SMOOTH);

		if ((Bi.getHeight() > height) || (Bi.getWidth() > width)) {
			if (Bi.getHeight() > Bi.getWidth())
				Ratio = (float)height / Bi.getHeight();
			else
				Ratio = (float)width / Bi.getWidth();
		}

		AffineTransformOp op = new AffineTransformOp(AffineTransform
				.getScaleInstance(Ratio, Ratio), null);
		Itemp = op.filter(Bi, null);
		try {
			ImageIO.write((BufferedImage) Itemp, "jpg", ThF);
		} catch (Exception ex) {
			throw new Exception(" ImageIo.write error in CreatThum.: "
					+ ex.getMessage());
		}
		return (true);
	}
}